package com.why.biyesheji.controller.mall;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.why.biyesheji.common.Constants;
import com.why.biyesheji.pojo.Shipping;
import com.why.biyesheji.service.IOrderService;
import com.why.biyesheji.service.IShippingService;
import com.why.biyesheji.util.Result;
import com.why.biyesheji.util.ResultGenerator;
import com.why.biyesheji.vo.MallUserVO;
import org.apache.catalina.LifecycleState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import sun.rmi.runtime.Log;

import javax.servlet.Registration;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by 华耀 王 on 2020/10/27
 **/
@Controller
public class OrderController {
    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Value("${file.address}")
    private String filePath;

    @Autowired
    private IShippingService iShippingService;

    @Autowired
    private IOrderService iOrderService;

    @GetMapping({"/order-confirm","/order-confirm.html"})
    public String orderConfirm(HttpSession session,
                               Model model,
                               @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                               @RequestParam(value = "pageSize",defaultValue = "10")int pageSize){
        MallUserVO mallUserVO = (MallUserVO) session.getAttribute(Constants.MALL_USER_SESSION_KEY);
        if (mallUserVO == null){
            return Constants.NEED_LOGIN;
        }
        Result shippingResult = iShippingService.shippingList(mallUserVO.getId(),pageNum,pageSize);
        Result productList = iOrderService.getProductList(mallUserVO.getId());
        PageInfo pageInfo = (PageInfo) shippingResult.getData();
        model.addAttribute("shippingResult",pageInfo.getList());
        model.addAttribute("productList",productList.getData());
        return "mall/order-confirm";
    }

    @PostMapping("/order-create")
    @ResponseBody
    public Result create(Integer shippingId,HttpSession session){
        MallUserVO mallUserVO = (MallUserVO) session.getAttribute(Constants.MALL_USER_SESSION_KEY);
        if (mallUserVO == null){
            return ResultGenerator.getFailResult(Constants.NEED_LOGIN);
        }
        return iOrderService.createOrder(mallUserVO.getId(),shippingId);
    }

    @GetMapping({"/order-list","/order-list.html"})
    public String orderList(HttpSession session,
                            Model model,
                            @RequestParam(value = "pageNum",defaultValue = "1")int pageNum,
                            @RequestParam(value = "pageSize",defaultValue = "10")int pageSize){
        MallUserVO mallUserVO = (MallUserVO) session.getAttribute(Constants.MALL_USER_SESSION_KEY);
        if (mallUserVO == null){
            return Constants.NEED_LOGIN;
        }
        Result orderList = iOrderService.getOrderList(mallUserVO.getId(), pageNum, pageSize);
        PageInfo pageInfo = (PageInfo) orderList.getData();
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("orderList",pageInfo.getList());
        return "mall/order-list";
    }

    @GetMapping({"/order-detail","/order-detail.html"})
    public String orderDetail(HttpSession session,Long orderNumber,Model model){
        MallUserVO mallUserVO = (MallUserVO) session.getAttribute(Constants.MALL_USER_SESSION_KEY);
        if (mallUserVO == null){
            return Constants.NEED_LOGIN;
        }
        Result orderDetail = iOrderService.getOrderDetail(mallUserVO.getId(), orderNumber);
        model.addAttribute("orderDetail",orderDetail.getData());
        return "mall/order-detail";
    }


    @PostMapping("/order-cancel")
    @ResponseBody
    public Result orderCancel(HttpSession session,Long orderNo){
        MallUserVO mallUserVO = (MallUserVO) session.getAttribute(Constants.MALL_USER_SESSION_KEY);
        if (mallUserVO == null){
            return ResultGenerator.getFailResult(Constants.NEED_LOGIN);
        }
        Result result = iOrderService.orderCancel(mallUserVO.getId(), orderNo);
        return result;
    }

    @PostMapping("/order-receive")
    @ResponseBody
    public Result orderReceive(HttpSession session,Long orderNo){
        MallUserVO mallUserVO = (MallUserVO) session.getAttribute(Constants.MALL_USER_SESSION_KEY);
        if (mallUserVO == null){
            return ResultGenerator.getFailResult(Constants.NEED_LOGIN);
        }
        Result result = iOrderService.orderReceive(mallUserVO.getId(), orderNo);
        return result;
    }








    @GetMapping({"/payment.html","/payment"})
    public String payment(){
        return "mall/payment";
    }


    @RequestMapping("/pay")
    @ResponseBody
    public Result pay(Long orderNo, HttpSession session) throws FileNotFoundException {
        MallUserVO mallUserVO = (MallUserVO) session.getAttribute(Constants.MALL_USER_SESSION_KEY);
        if (mallUserVO == null){
            return ResultGenerator.getFailResult(Constants.NEED_LOGIN);
        }
        //文件上传的路径
        File path = new File(filePath);
        File upload = new File(path.getAbsolutePath(), "/upload");
        String filePath = upload.toString();
        Result pay = iOrderService.pay(mallUserVO.getId(), orderNo, filePath);
        return pay;

    }


    /**
     * 授权回调地址
     *
     * netapp进行内网穿透获取支付宝的回调参数
     * @param request
     * @return
     */
//    @RequestMapping(value = "alipay_callback.do",method = RequestMethod.POST)
    @RequestMapping("alipay_callback")
    @ResponseBody
    public Object alipayCallback(HttpServletRequest request) {
        Map<String,String> params = Maps.newHashMap();

        Map requestParameterMap = request.getParameterMap();
        for (Iterator iter = requestParameterMap.keySet().iterator();iter.hasNext();){
            String keyName = (String) iter.next();
            String[] values = (String[]) requestParameterMap.get(keyName);
            String valuesStr = "";
            for (int i = 0; i < values.length; i++) {
                valuesStr =(i == values.length-1) ? valuesStr + values[i] :valuesStr + values[i] + ",";
            }
            params.put(keyName,valuesStr);
        }
        logger.info("支付宝回调,sign:{},trade_status:{},参数:{}",params.get("sign"),params.get("trade_status"),params.toString());

        // 然后要验证，回调的正确性，是不是支付宝发的，避免重复通知
        /*异步返回结果验签
          在通知返回参数列表中，除去 sign、sign_type 两个参数外，凡是通知返回回来的参数皆是待验签的参数；*/
//        支付宝提供的方法只除去了sign，需要我们手动除去
        params.remove("sign_type");
        try {
            boolean alipayRSACheckedV2 = AlipaySignature.rsaCheckV2(params, Configs.getAlipayPublicKey(),"utf-8",Configs.getSignType());
            if (!alipayRSACheckedV2){
                return ResultGenerator.getFailResult("非法请求，再恶意请求将报警处理！");
            }
        } catch (AlipayApiException e) {
            logger.info("支付宝验证回调异常"+e);
        }
        // todo 验证数据

        Result alipayCallBack = iOrderService.alipayCallBack(params);
        if (alipayCallBack.isSuccess()){
            return Constants.AlipayCallBack.RESPONSE_SUCCESS;
        }
        return Constants.AlipayCallBack.RESPONSE_FAILED;
    }

    /**
     * 查询订单支付状态是否成功
     * @param session
     * @param orderNo
     * @return
     */
    @RequestMapping("query_order_pay_status")
    @ResponseBody
    public Result<Boolean> queryOrderPayStatus(HttpSession session, Long orderNo){
        MallUserVO mallUserVO = (MallUserVO) session.getAttribute(Constants.MALL_USER_SESSION_KEY);
        if (mallUserVO == null){
            return ResultGenerator.getFailResult(Constants.NEED_LOGIN);
        }
        Result result = iOrderService.queryOrderPayStatus(mallUserVO.getId(), orderNo);
        if (result.isSuccess()){
            return ResultGenerator.getSuccessResult(true);
        }
        return ResultGenerator.getSuccessResult(false);

    }


}
